/*
 *  Copyright 2007 Google Inc.

 * 	Licensed under the Apache License, Version 2.0 (the "License");
 *	you may not use this file except in compliance with the License.
 *	You may obtain a copy of the License at
 
 *  	http://www.apache.org/licenses/LICENSE-2.0

 *	Unless required by applicable law or agreed to in writing, software
 *	distributed under the License is distributed on an "AS IS" BASIS,
 *	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *	See the License for the specific language governing permissions and
 *	limitations under the License.

 */

package com.byjyate.rssdreamwork;

import java.net.*;
import java.util.Collections;
import javax.cache.*;
import com.google.appengine.api.taskqueue.*;
import com.google.appengine.api.taskqueue.TaskOptions.*;

public class CachedHtmlFetcher extends HtmlFetcher {
	private String url;

	public CachedHtmlFetcher(String url) throws MalformedURLException {
		super(url);
		this.url = url;
	}

	@SuppressWarnings("unchecked")
	public String getCachedContent() {
        Cache cache = null;

        try {
            CacheFactory cacheFactory = CacheManager.getInstance().getCacheFactory();
            cache = cacheFactory.createCache(Collections.emptyMap());
            String value = (String) cache.get(url);
            if (value != null) 
            	return value;

			PageInfoRepository pageInfoRepo = new PageInfoRepository();
			PageInfo pageInfo = pageInfoRepo.getPageInfo(url);
			if (pageInfo != null && !pageInfo.getStatus().equals(PageInfoRepository.WAITING))
			{
				value = pageInfo.getContent();
				cache.put(url, value);
				cache.remove("tasklist");
				return value;
			}
			if (pageInfoRepo.addPageInfo(url)) {
				Queue queue = QueueFactory.getDefaultQueue();
				queue.add(Builder.withUrl("/tasks/fetchpage").param("url", url));
			}
			pageInfoRepo.close();
			return null;
        } catch (CacheException e) {return null;}
	}
}
